package com.wenjiang.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.wenjiang.common.lang.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 处理 认证异常的 处理器
 */
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {

        // 告诉浏览器 要用utf-8 进行解析 否则中文乱码
        httpServletResponse.setHeader("Content-type", "text/html;charset=UTF-8");

        PrintWriter writer = httpServletResponse.getWriter();

        ObjectMapper objectMapper =new ObjectMapper();

        writer.write(objectMapper.writeValueAsString(Result.fail(401, "用户未登录")));
    }
}
